package com.module.overview.ui.cardHistoryDetails

import android.view.View
import androidx.core.content.ContextCompat
import com.common.app.data.bean.CalendarDay
import com.common.app.data.bean.CommonMeasureResultModel
import com.common.app.data.bean.KeyEvents
import com.common.app.data.bean.KeyPre
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.base.utils.SpUtilsManagement
import com.common.base.app.extras.no
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.showToast
import com.common.base.app.extras.yes
import com.common.base.app.fragment.BaseVMFragment
import com.common.base.utils.ToastUtils
import com.common.base.utils.ViewUtils
import com.common.base.widget.animator.CustomAnimation1
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.ble.utils.AizoSDKUtil
import com.module.ble.utils.AllCardTypeConfig
import com.module.overview.R
import com.module.overview.databinding.OverviewFragmentCardHistoryDetailsBinding
import com.module.overview.ui.cardHistoryDetails.provider.OvSignsHrCardProvider
import com.module.overview.ui.cardHistoryDetails.provider.OvSignsOxyCardProvider
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2024/8/22
 *
 * 描述：
 *
 * 修订历史：
 *
 */
class CardHistoryDetailsFragment :
    BaseVMFragment<OverviewFragmentCardHistoryDetailsBinding, CardHistoryDetailsViewModel>(),
    View.OnClickListener, MeasurementPromptDialog.OnMeasurementPromptListener,
    InMeasurementDialog.OnInMeasurementListener {

    companion object {
        fun newInstance(mCalendar: CalendarDay?=null, mTitle: String): CardHistoryDetailsFragment {
            val fragment = CardHistoryDetailsFragment()
            fragment.mCalendar = mCalendar
            fragment.mTitle = mTitle
            return fragment
        }
    }

    private var mCalendar: CalendarDay? = null

    private var mTitle = "all"

    private val measurementPromptDialog by lazy { MeasurementPromptDialog(requireContext()) }
    private val inMeasurementDialog by lazy { InMeasurementDialog(requireContext()) }

    private var measurementType = 0

    override fun getPlaceholderView() = mViewBinding.placeHolderView

    override fun getViewModel() = CardHistoryDetailsViewModel::class.java

    override fun getViewBinding() =
        OverviewFragmentCardHistoryDetailsBinding.inflate(layoutInflater)

    private val mAdapter by lazy { OverviewHistoryDetailsCardAdapter(mCalendar) }

    override fun initViews() {
        super.initViews()

        mViewBinding.pdView.setEnableLoadMore(false)
        //上下拉刷新
        getRefreshFooter()?.let { mViewBinding.pdView.setRefreshFooter(it) }
        mViewBinding.pdView.setRefreshHeader(
            ClassicsHeader(requireActivity()).setAccentColor(
                ContextCompat.getColor(requireActivity(), R.color.text_content_week)
            )
        )

        mViewBinding.pdView.setRefreshFooter(
            ClassicsFooter(requireActivity()).setAccentColor(
                ContextCompat.getColor(
                    requireActivity(),
                    R.color.color_999999
                )
            )
        )

        mAdapter.apply {
            adapterAnimation = CustomAnimation1()
            isAnimationFirstOnly = true
            addFooterView(layoutInflater.inflate(R.layout.base_rlv_margin_footer_tr_view50, null))
            mViewBinding.hrv.adapter = this
        }

        measurementPromptDialog.setListener(this)
        inMeasurementDialog.setListener(this)
    }

    override fun lazyInitData() {
        super.lazyInitData()
//        mViewBinding.tvTimeTip.text = mType?:"----"

        val mList = mutableListOf<HistoryDetailsModel>()
        when (mTitle) {
            getString(R.string.common_sleep_hint) -> {
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_SLEEP_STATE_VALUE))
//                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_SLEEP_SUB_SCORING))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_SLEEP_TOTAL_DURATION))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_SLEEP_TOTAL_PERIOD))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_SLEEP_NAP_RECORD_PERIOD))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_SLEEP_SUMMARY_PERIOD))
            }

            getString(R.string.common_activity_hint) -> {
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_ACTIVITY_STATE_VALUE))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_ACTIVITY_STEP_NUM))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_ACTIVITY_CALORIE))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_ACTIVITY_DAY_CALORIE))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_ACTIVITY_STANDING_DURATION))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_ACTIVITY_DAY_STRENGTH))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_ACTIVITY_DAY_RATIO))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_ACTIVITY_RECORD))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_ACTIVITY_SUMMARY))
            }

            getString(R.string.common_pressure_hint) -> {
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_PRESSURE_STATE_VALUE))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_PRESSURE_DISTRIBUTION))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_PRESSURE_RATIO))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_PRESSURE_SLEEP))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_PRESSURE_SUMMARY))

            }

            getString(R.string.common_signs_hint) -> {
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_SIGNS_STATE_VALUE))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_SIGNS_HR))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_SIGNS_OXY))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_SIGNS_HRV))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_SIGNS_TEMP))
                mList.add(HistoryDetailsModel(itemType = AllCardTypeConfig.TYPE_CARD_SIGNS_RES_RATE))

            }

            getString(R.string.common_exercise_hint) -> {

            }

            getString(R.string.common_period_hint) -> {

            }

        }
        mAdapter.setList(mList)
    }

    override fun initEvents() {
        super.initEvents()
        setErrorRetryListener {
            lazyInitData()
        }


        LiveEventBus.get(KeyEvents.KEY_OV_SET_HR_MEASUREMENT_LISTENER).observe(this) {
            if (mCalendar?.dateName == getString(R.string.common_today_hint)) {
                (mAdapter.getCusItemProvider(AllCardTypeConfig.TYPE_CARD_SIGNS_HR) as OvSignsHrCardProvider).let { providerIt->
                    providerIt.tvMeasure?.setOnClickListener {
                        if (!AizoSDKUtil.isConnect()) {
                            showToast(getString(R.string.ble_device_disconnect))
                            return@setOnClickListener
                        }
                        measurementType = 1
                        SpUtilsManagement.getBoolean(KeyPre.KEY_NO_SHOW_MEASUREMENT_PROMPT,false).no {
                            measurementPromptDialog.show()
                        }.otherwise {
                            inMeasurementDialog.show(measurementType)
                        }
                    }
                }
            }
        }
        LiveEventBus.get(KeyEvents.KEY_OV_SET_OXY_MEASUREMENT_LISTENER).observe(this) {
            if (mCalendar?.dateName == getString(R.string.common_today_hint)) {
                (mAdapter.getCusItemProvider(AllCardTypeConfig.TYPE_CARD_SIGNS_OXY) as OvSignsOxyCardProvider).let { providerIt->
                    providerIt.tvMeasure?.setOnClickListener {
                        if (!AizoSDKUtil.isConnect()) {
                            showToast(getString(R.string.ble_device_disconnect))
                            return@setOnClickListener
                        }
                        measurementType = 2
                        SpUtilsManagement.getBoolean(KeyPre.KEY_NO_SHOW_MEASUREMENT_PROMPT,false).no {
                            measurementPromptDialog.show()
                        }.otherwise {
                            inMeasurementDialog.show(measurementType)
                        }
                    }
                }
            }
        }
        LiveEventBus.get(KeyEvents.KEY_MEASURE_HVO_RESULT, CommonMeasureResultModel::class.java).observe(this){

            when (it.measureType) {
                1 -> {
                    (mAdapter.getCusItemProvider(AllCardTypeConfig.TYPE_CARD_SIGNS_HR) as OvSignsHrCardProvider).let { providerIt ->
                        providerIt.measureResult = it.value
                        providerIt.tvAverageHr?.text = providerIt.measureResult.toInt().toString()
                        providerIt.getTheDayHr()
                    }
                }
                2 -> {
                    (mAdapter.getCusItemProvider(AllCardTypeConfig.TYPE_CARD_SIGNS_OXY) as OvSignsOxyCardProvider).let { providerIt ->
                        providerIt.measureResult = it.value
                        providerIt.tvAverageOxy?.text = providerIt.measureResult.toInt().toString()
                    }
                }
                6 -> {
                }
            }
        }

        mViewBinding.pdView.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                resetData()
//                mViewModel.earlyMorningStr.post("51")
//                mViewModel.morningStr.post("41")
//                mViewModel.afternoonStr.post("31")
//                mViewModel.eveningStr.post("--")
//
//                stressData[18].selectBg = true
//                mViewBinding.stressChart.invalidate()
//
//                setAllRatioCardNotSelect()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                getDataList()
            }
        })

//        mViewBinding.tvEarlyMorningCk.setOnClickListener(onClick = this)

//       mViewModel.earlyMorningStr.observe(this){
//           SpanUtils.create()
//               .addForeColorSection(
//                   "${getString(R.string.common_early_morning_unit)}\n",
//                  if (mViewBinding.tvEarlyMorningCk.isSelected) ViewUtils.getColor(R.color.c_5282ff) else  ViewUtils.getColor(R.color.c_7f7f7f)
//               )
//               .addForeColorSection(it, if (mViewBinding.tvEarlyMorningCk.isSelected) ViewUtils.getColor(R.color.c_5282ff) else  ViewUtils.getColor(R.color.text_content))
//               .setAbsSize(it, 16)
//               .setStyle(it, Typeface.BOLD)
//               .showIn(mViewBinding.tvEarlyMorningCk)
//       }
//        mViewModel.morningStr.observe(this){
//            SpanUtils.create()
//                .addForeColorSection(
//                    "${getString(R.string.common_morning_unit)}\n",
//                    if (mViewBinding.tvMorningCk.isSelected) ViewUtils.getColor(R.color.c_5282ff) else  ViewUtils.getColor(R.color.c_7f7f7f)
//                )
//                .addForeColorSection(it, if (mViewBinding.tvMorningCk.isSelected) ViewUtils.getColor(R.color.c_5282ff) else  ViewUtils.getColor(R.color.text_content))
//                .setAbsSize(it, 16)
//                .setStyle(it, Typeface.BOLD)
//                .showIn(mViewBinding.tvMorningCk)
//        }
//        mViewModel.afternoonStr.observe(this){
//            SpanUtils.create()
//                .addForeColorSection(
//                    "${getString(R.string.common_afternoon_unit)}\n",
//                    if (mViewBinding.tvAfternoonCk.isSelected) ViewUtils.getColor(R.color.c_5282ff) else  ViewUtils.getColor(R.color.c_7f7f7f)
//                )
//                .addForeColorSection(it, if (mViewBinding.tvAfternoonCk.isSelected) ViewUtils.getColor(R.color.c_5282ff) else  ViewUtils.getColor(R.color.text_content))
//                .setAbsSize(it, 16)
//                .setStyle(it, Typeface.BOLD)
//                .showIn(mViewBinding.tvAfternoonCk)
//        }
//        mViewModel.eveningStr.observe(this){
//            SpanUtils.create()
//                .addForeColorSection(
//                    "${getString(R.string.common_evening_unit)}\n",
//                    if (mViewBinding.tvEveningCk.isSelected) ViewUtils.getColor(R.color.c_5282ff) else  ViewUtils.getColor(R.color.c_7f7f7f)
//                )
//                .addForeColorSection(it, if (mViewBinding.tvEveningCk.isSelected) ViewUtils.getColor(R.color.c_5282ff) else  ViewUtils.getColor(R.color.text_content))
//                .setAbsSize(it, 16)
//                .setStyle(it, Typeface.BOLD)
//                .showIn(mViewBinding.tvEveningCk)
//        }

    }

    override fun onClick(v: View?) {
        when (v) {
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    private fun finishPdView() {
        mViewBinding.pdView.finishRefresh()
        mViewBinding.pdView.finishLoadMore()
    }

    fun resetData(showLoading: Boolean = false) {
        getDataList(showLoading)
    }

    fun getDataList(showLoading: Boolean = false) {
        showLoading.yes { showDialogLoading() }
        finishPdView()
    }

    fun updateDateData(mData: String?) {
        lazyInitData()
    }

    fun measurementFailure(){
        ToastUtils.showToast(
            "${ViewUtils.getString(R.string.ble_health_check_fail)},${
                ViewUtils.getString(
                    R.string.ble_health_retest_check_run
                )
            }!"
        )

        (mAdapter.getCusItemProvider(AllCardTypeConfig.TYPE_CARD_SIGNS_HR) as OvSignsHrCardProvider).let {
            it.tvMeasure?.isEnabled = true
        }
        (mAdapter.getCusItemProvider(AllCardTypeConfig.TYPE_CARD_SIGNS_OXY) as OvSignsOxyCardProvider).let {
            it.tvMeasure?.isEnabled = true
        }
    }

    override fun onMeasurementPromptClick() {
        measurementPromptDialog.dismiss()
        inMeasurementDialog.show(measurementType)
    }

    override fun onInMeasurementClick() {

    }
}